package com.zcbl.toolkit.util;

import com.zcbl.toolkit.exception.SystemRuntimeException;
import org.springframework.util.Assert;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Objects;

/**
 * @author he peng
 * @create 2018/4/25 17:51
 * @see
 */
public class IOUtils {

    public static void copyEffectiveByte(ByteArrayOutputStream source, ByteBuffer dest, byte[] buf) {
        Assert.notNull(source, "outputStream == null");
        Assert.notNull(dest, "byteBuffer == null");
        if (Objects.isNull(buf) || buf.length == 0) {
            buf = new byte[1024 * 40];
        }
        int originalEffectiveSize = source.size();
        int copiedSize = 0;
        while (copiedSize < originalEffectiveSize) {
            if (source.size() > buf.length) {
                source.write(buf , 0 , buf.length);
                dest.put(buf , 0 , buf.length);
                copiedSize += buf.length;
            } else {
                source.write(buf , 0 , source.size());
                dest.put(buf , 0 , source.size());
                copiedSize += source.size();
            }
        }
    }

    public static void close(Closeable closeable) {
        if (Objects.nonNull(closeable)) {
            try {
                closeable.close();
            } catch (IOException e) {
                throw new SystemRuntimeException(e.getMessage() , e);
            }
        }
    }

}
